package rmi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


public class Server {

	public static void main(String[] args) {
		try {
			System.out.println("starting servant ...");
			LocateRegistry.createRegistry(6789);
			Hello servant = new HelloImpl();
			Naming.rebind("rmi://localhost:6789/hello", servant);
			HelloTakeSetArg servant2 = new HelloTakeSetArgImpl();

			Naming.rebind("rmi://localhost:6789/hello2", servant2);

			System.out.println("binding finished");
		} catch (RemoteException | MalformedURLException e) {
			e.printStackTrace();
		}
	}
}

class HelloImpl extends UnicastRemoteObject implements Hello {

	protected HelloImpl() throws RemoteException {
		super();
	}

	public String hello(String name) throws RemoteException {
		System.out.println("HelloImpl.hello");
		return "Hello, " + name;
	}
}

class HelloTakeSetArgImpl extends UnicastRemoteObject implements HelloTakeSetArg {

	Map<String, Integer> count = new HashMap<>();

	protected HelloTakeSetArgImpl() throws RemoteException {
	}


	@Override
	public JSONObject hello(JSONArray names) throws RemoteException {
		System.out.println("rmi.HelloTakeSetArgImpl.hello(com.alibaba.fastjson.JSONArray)");
		return new JSONObject().fluentPutAll(names.toJavaList(String.class).stream().collect(Collectors.toMap(n -> n, n -> count.merge(n, 1, (v1, v2) -> v1 + v2))));
	}

	@Override
	public HashMap<String, Integer> hello(HashSet<String> names) throws RemoteException {
		System.out.println("rmi.HelloTakeSetArgImpl.hello(java.util.HashSet<java.lang.String>)");
		return names.stream().collect(Collectors.toMap(n -> n, n -> count.merge(n, 1, (v1, v2) -> v1 + v2), (v1, v2) -> v1 + v2, () -> new HashMap<>()));
	}

	public Map<String, Integer> hello(Set<String> names) throws RemoteException {
		System.out.println("rmi.HelloTakeSetArgImpl.hello(java.util.Set<java.lang.String>)");
		return names.stream().collect(Collectors.toMap(n -> n, n -> count.merge(n, 1, (v1, v2) -> v1 + v2)));
	}
}